<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_Spot
{
    public static $_typeid = 5;

    /**
     * @desc 景点列表
     * @param $params
     * @return array
     */
    public static function search($params)
    {
        /**
         * @var $attr_id
         * @var $price_id
         * @var $sort_type
         * @var $dest_py
         * @var $keyword
         * @var $lat
         * @var $lng
         */
        extract($params);

        $pagesize = Arr::get($params, 'pagesize', 5);
        $page     = Arr::get($params, 'page', 1);
        $platform_no = $params['platform_no'];

        $add_field = '';
        if (!empty($lat) && !empty($lng)) {
            $lat       = round($params['lat'], 3);
            $lng       = round($params['lng'], 3);
            $add_field = ",ROUND(6378.138*2*ASIN(SQRT(POW(SIN((" . $lat . "*PI()/180-FORMAT(`sline_spot`.lat,3)*PI()/180)/2),2)+COS(" . $lat . "*PI()/180)*COS(FORMAT(`sline_spot`.lat,3)*PI()/180)*POW(SIN((" . $lng . "*PI()/180-FORMAT(`sline_spot`.lng,3)*PI()/180)/2),2)))*1000) AS distance";
        }

        $field = "`sline_spot`.lat,`sline_spot`.lng,`sline_spot`.id,`sline_spot`.title,`sline_spot`.sellpoint";
        $field .= ",`sline_spot`.attrid,`sline_spot`.iconlist,`sline_spot`.satisfyscore,`sline_spot`.litpic";
        $field .= ",(IFNULL(`sline_spot`.bookcount,0)+IFNULL(`sline_member_order_statistic`.sell_num,0)) AS sell_num";
        $field .= $add_field;

        $builder = DB::select(DB::expr($field))
            ->from('spot');

        //排序
        $order_by = "";
        if (!empty($sort_type)) {
            if ($sort_type == 1)//价格升序
            {
                $order_by = " `sline_spot`.price ASC,";
            } else if ($sort_type == 2) //价格降序
            {
                $order_by = " `sline_spot`.price DESC,";
            } else if ($sort_type == 3) //销量降序
            {
                $order_by = " sell_num DESC,";
            } else if ($sort_type == 4)//推荐
            {
                $order_by = " `sline_spot`.recommendnum DESC,";
            }
        }

        //按目的地搜索
        if ($dest_py && $dest_py != 'all') {
            $dest_id = Model_Destinations::get_id_by_pinyin($dest_py);
        }

        // 提前处理真实购买量
        $builder->join('member_order_statistic', 'left')
            ->on('member_order_statistic.product_id', '=', DB::expr('`sline_spot`.id'))
            ->on('member_order_statistic.type_id', '=', self::$_typeid);


        if (!empty($lat) && !empty($lng)) {
            $lat       = round($params['lat'], 3);
            $lng       = round($params['lng'], 3);
            $distance  = $params['distance'];
            $add_where = "`sline_spot`.lat>0 and `sline_spot`.lng>0 and ROUND(6378.138*2*ASIN(SQRT(POW(SIN((" . $lat . "*PI()/180-FORMAT(`sline_spot`.lat,3)*PI()/180)/2),2)+COS(" . $lat . "*PI()/180)*COS(FORMAT(`sline_spot`.lat,3)*PI()/180)*POW(SIN((" . $lng . "*PI()/180-FORMAT(`sline_spot`.lng,3)*PI()/180)/2),2)))*1000)<$distance ";
            $builder->and_where(DB::expr($add_where));
            $builder->and_where(DB::expr(" and FIND_IN_SET({$platform_no},sline_spot.platform)"));
        } else if (!empty($dest_id)) {
            $builder->join('kindorderlist', 'left')
                ->on('spot.id', '=', DB::expr('`sline_kindorderlist`.aid'))
                ->on('spot.webid', '=', DB::expr('`sline_kindorderlist`.webid'))
                ->on('kindorderlist.typeid', '=', self::$_typeid)
                ->on('kindorderlist.classid', '=', DB::expr("{$dest_id}"));
            $builder->and_where(DB::expr("FIND_IN_SET('$dest_id',sline_spot.kindlist)"));
            $builder->and_where(DB::expr(" and FIND_IN_SET({$platform_no},sline_spot.platform)"));
            $order_by .= "IFNULL(`sline_kindorderlist`.displayorder,9999) ASC,";
        } else {
            $builder->join('allorderlist', 'left')
                ->on('spot.id', '=', DB::expr('`sline_allorderlist`.aid'))
                ->on('spot.webid', '=', DB::expr('`sline_allorderlist`.webid'))
                ->on('allorderlist.typeid', '=', self::$_typeid);
            $builder->where(DB::expr(" FIND_IN_SET({$platform_no},sline_spot.platform)"));
            $order_by .= "IFNULL(`sline_allorderlist`.displayorder,9999) ASC,";
        }

        //价格区间
        if ($price_id) {
            $price_arr = DB::select()
                ->from('spot_pricelist')
                ->where('id', '=', $price_id)
                ->execute()
                ->current();
            if (!empty($price_arr)) {
                if (empty($price_arr['min'])) {
                    $builder->and_where('spot.price', '<', $price_arr['max']);
                } elseif (empty($price_arr['max'])) {
                    $builder->and_where('spot.price', '>', $price_arr['min']);
                } else {
                    $builder->and_where(DB::expr(" AND sline_spot.price BETWEEN {$price_arr['min']} AND {$price_arr['max']}"));
                }
            }
        }

        //按属性
        if (!empty($attr_id)) {
            $attr_where = self::get_attr_where($attr_id);
            if ($attr_where) {
                $builder->and_where(DB::expr($attr_where));
            }
        }

        //按关键词
        if (!empty($keyword)) {
            $builder->and_where('spot.title', 'like', '%' . $keyword . '%');
        }

        $total = $builder->execute()->count();

        if ($page && $pagesize) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }

        $list = $builder->order_by(DB::expr("{$order_by}sline_spot.modtime DESC,sline_spot.addtime DESC"))
            ->execute()
            ->as_array();

        return array(
            'total' => $total,
            'list' => $list
        );
    }

    /**
     * 景点详情
     * @param $params
     * @return array|mixed
     * @throws Kohana_Exception
     */
    public static function detail($params)
    {
        $id     = $params['id'];
        $userid = $params['userid'];
        $platform_no = $params['platform_no'];
        $info   = DB::select()
            ->from('spot')
            ->where('id', '=', $id)
            ->and_where(DB::expr(" and FIND_IN_SET({$platform_no},platform)"))
            ->execute()
            ->current();
        if (!$info) {
            return array();
        }

        //属性列表
        $info['attr_list'] = Model_Spot::spot_attr($info['attrid']);

        // 价格
        $price = Model_Spot::get_minprice($info['id'], array('info' => $info));
        $info['price'] = $price['price'];

        //是否售罄
        $info['sell_out'] = St_Functions::is_sell_out(5,$info['id']);

        // 折扣金额
        $info['discount_min_price'] = $userid ? Model_Api_V2_Discount::get_discount($userid, self::$_typeid, $id, $info['price']) : '';

        //点评数
        $info['comment_num'] = Model_Comment::get_comment_num($info['id'], self::$_typeid);

        // 销售数量
        $info['sell_num'] = Model_Member_Order_statistic::get_sell_num(self::$_typeid, $info['id']) + intval($info['bookcount']);

        // 产品编号
        $info['series'] = St_Product::product_series($info['id'], self::$_typeid);

        // 满意度
        $info['score'] = St_Functions::get_satisfy(self::$_typeid, $info['id'], $info['satisfyscore']);
        $info['satisfy'] = $info['score']?str_replace('%','',$info['score']):'';
        // 封面图片
        $info['litpic'] = empty($info['litpic']) ? Common::nopic() : $info['litpic'];

        // 扩展字段信息
        $extend_info         = ORM::factory('spot_extend_field')
            ->where('productid', '=', $info['id'])
            ->find()
            ->as_array();
        $info['extend_info'] = $extend_info;

        // 套餐信息
        $info['suit_list'] = self::suit($info['id'], $params);
        $info['rank_name'] = Model_Member::member_rank($userid, array('return' => 'current'));
        // 会员折扣
        foreach ($info['suit_list'] as &$item) {
            $discount_min_price = '';
            if ($userid) {
                $discount_min_price = Model_Api_V2_Discount::get_discount($userid, self::$_typeid, $id, $item['price']['price']);
            }
            $item['discount_min_price'] = $discount_min_price;
        }

        // 景点详情内容
        $params                 = array(
            'typeid' => self::$_typeid,
            'productinfo' => $info,
            'onlyrealfield' => 1,
            'pc' => 0
        );
        $info['introduce_list'] = self::get_detail_content($params);

        return $info;
    }


    /**
     * @desc 属性生成where条件,用于多条件属性搜索
     * @param $attrid
     * @return string
     */
    public static function get_attr_where($attrid)
    {
        $arr = Common::remove_arr_empty(explode('_', $attrid));
        $str = '';
        foreach ($arr as $value) {
            $value = intval($value);
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,sline_spot.attrid) ";
            }
        }
        return $str;
    }

    /**
     * 获取景点套餐列表
     * @param $product_id
     * @param $params
     * @return array
     */
    private static function suit($product_id, $params)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认'
        );

        $query = DB::select()->from('spot_ticket')
            ->where('spotid', '=', $product_id);
        if ($params['card_suit_id']) {
            $query->where('id', 'IN', explode(',', $params['card_suit_id']));
        }
        $suit = $query->and_where('status', '=', '3')
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();

        foreach ($suit as &$r) {
            $before_book       = array(
                'ticketid' => $r['id'],
                'info' => $r
            );
            $r['price']    = Model_Spot::get_minprice($r['spotid'], $before_book);
            $r['sell_out'] = St_Functions::is_sell_out(5, $r['spotid'], $r['id']);
            $r['paytype_name'] = $pay_name[$r['paytype']];
        }
        return $suit;
    }

    /**
     * @desc 获取景点详细内容
     * @param $params
     * @return array
     */
    private static function get_detail_content($params)
    {

        $default = array(
            'typeid' => self::$_typeid,
            'productinfo' => 0,
            'onlyrealfield' => 1,
            'pc' => 0

        );
        $params  = array_merge($default, $params);
        extract($params);
        $arr = DB::select()->from('spot_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $ar        = DB::select()
            ->from('spot_extend_field')
            ->where('productid', '=', $productid)
            ->execute()
            ->as_array();

        $list = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian') {
                continue;
            }
            if ($v['isrealfield'] == 1) {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ?: '';
            }
            if (empty($content)) {
                continue;
            }

            $a                = array();
            $a['columnname']  = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] = Model_Api_V2_Xcx::filter_content($content);
            $list[]       = $a;

        }
        return $list;
    }

    /**
     * 获取价格
     * @param $spot
     * @param $ticket_info
     * @param $request_params
     * @return array
     * @throws Exception
     */
    public static function get_calendar_price($spot, $ticket_info, $request_params)
    {
        /**
         * @var $rows
         * @var $year
         * @var $month
         * @var $suit_id
         * @var $mid
         */
        extract($request_params);

        $sku_id = Arr::get($request_params,'sku_id', 0);
        if ($year && $month) {
            $start_date = "{$year}-{$month}-1";
            $days       = date('t', $start_date);
            $end_date   = "{$year}-{$month}-{$days}";
        } else {
            $date_before = DB::select()->from('spot_ticket')->where('id','=',$suit_id)->execute()->current();
            $day_before  = $date_before['day_before']*86400;
            $day_before += $date_before['hour_before']>0?$date_before['hour_before']*3600:0;
            $day_before += $date_before['minute_before']>0?$date_before['minute_before']*60:0;

            $now_day =strtotime(date('Y-m-d',time()));
            $start_date = date('Y-m-d', $now_day+$day_before);
            $end_date   = date('Y-m-d', strtotime("+1 year"));
        }

        $spot_id = $spot['id'];
        // 预订规则使用的套餐判断套餐
        if ($spot['is_open_multiple_ticket'] == 1) {
            $tickets = Model_Spot_Ticket::get_on_sale_ticket(array('spot_id' => $spot_id));
        } else {
            $tickets = array($ticket_info);
        }

        $price_calendar = array();
        $params = array(
            'start_date' => $start_date,
            'end_date' => $end_date,
            'is_open' => 1,
            'rows' => $rows,
            'min_stock' => 1
        );
        foreach ($tickets as $ticket) {
            $calendar_params = $params;
            // 处理提前预订时间
            $before_time = Model_Spot_Ticket::get_before_time($ticket);
            if ($before_time && strtotime($params['start_date']) < $before_time) {
                $calendar_params['start_date'] = date("Y-m-d H:i:s", $before_time);
            }
            // 检查门票是否有规格
            $has_sku = Model_Spot_Ticket_Sku::ticket_has_sku($ticket['id']);
            $calendar_params['has_sku'] = $has_sku;
            // 获取价格日历
            $calendars = Model_Spot_Ticket_Price::get_price_calendar($spot_id, array('ticket_id' => $ticket['id'], 'sku_id' => $sku_id), $calendar_params);
            $price_number = 0;
            foreach ($calendars as $calendar) {
                if($rows && $rows == $price_number) {
                    break;
                }
                if (isset($price_calendar[$calendar['day']])) {
                    $adult_price = $price_calendar[$calendar['day']]['adultprice'];
                    $price       = floatval(Currency_Tool::price($calendar['price']));
                    $price_calendar[$calendar['day']]['adultprice'] = min($price, $adult_price);
                } else {
                    $price_calendar[$calendar['day']] = array(
                        'd' => intval(date('d', $calendar['day'])),
                        'date' => date('m-d', $calendar['day']),
                        'fulldate' => date('Y-m-d', $calendar['day']),
                        'adultprice' => floatval(Currency_Tool::price($calendar['price'])),
                        'number' => $calendar['stock'] ?? ''
                    );
                }
                $price_number ++;
            }
        }

        if(!empty($price_calendar)){
            ksort($price_calendar, SORT_STRING);
            if($rows) {
                $price_calendar = array_slice($price_calendar, 0, $rows);
            }
        }

        return array_values($price_calendar);
    }

    /**
     * 添加游客
     * @param $tourists
     * @param $order_id
     * @return void
     * @throws Kohana_Exception
     */
    public static function add_order_tourists($tourists, $order_id)
    {
        if ($tourists && is_array($tourists)) {
            foreach ($tourists as $v) {
                $arr = array(
                    'orderid' => $order_id,
                    'tourername' => $v['tourername'],
                    'sex' => $v['sex'],
                    'mobile' => $v['mobile'],
                    'cardtype' => $v['cardtype'],
                    'cardnumber' => $v['cardnumber']
                );
                DB::insert('member_order_tourer', array_keys($arr))->values(array_values($arr))->execute();
            }
        }
    }

    /**
     * 检查预订参数
     * @param $request_data
     * @param $member_id
     * @return array
     * @throws Exception
     */
    public static function check_order_params($request_data, $member_id)
    {
        $info = DB::select()
            ->from('spot')
            ->where('id', '=', $request_data['product_id'])
            ->where('ishidden', '=', 0)
            ->execute()
            ->current();
        if (empty($info)) {
            throw new Exception('景点不存在');
        }


        $link_info = json_decode($request_data['link_info'], true);
        if (!$link_info || !is_array($link_info)) {
            throw new Exception('请提交联系人信息');
        }

        if (!isset($link_info['name']) || !$link_info['name']) {
            throw new Exception('请填写联系人姓名');
        }

        if (!isset($link_info['phone']) || !$link_info['phone']) {
            throw new Exception('请填写联系人电话');
        }

        // 验证电话格式是否正确
        if (!preg_match("/^1[123456789]\d{9}$/", $link_info['phone'])) {
            throw new Exception('联系电话人格式不正确');
        }



        $suit_info = Model_Spot_Suit::suit_info($request_data['suit_id']);
        if (empty($suit_info)) {
            throw new Exception('套餐不存在');
        }

        if ($suit_info['status'] != 3) {
            throw new Exception('该套餐已下架');
        }

        //出发日期
        $use_date = $request_data['use_date'];
        if (strtotime($use_date) < strtotime(date('Y-m-d', time()))) {
            throw new Exception('日期不正确');
        }

        $check_result = Model_Spot::before_order_check($request_data['product_id'], $request_data['suit_id'], strtotime($request_data['use_date']));
        if (empty($check_result)) {
            throw new Exception('库存不足');
        }

        $ticket_price = DB::select()
            ->from('spot_ticket_price')
            ->where('ticketid', '=', $request_data['suit_id'])
            ->and_where('day', '=', strtotime($request_data['use_date']))
            ->and_where('supplier_channel_id', '=', 1)
            ->execute()
            ->current();
        if (empty($ticket_price)) {
            throw new Exception('获取报价失败');
        }

        $ding_num = $request_data['ding_num'];

        // 拼团
        $together_id = $request_data['together_id'];
        $join_id     = $request_data['join_id'];
        if ($together_id > 0 || $join_id > 0) {
            if (St_Functions::is_normal_app_install('together')) {
                $together_params      = array('join_id' => $join_id, 'ding_num' => $ding_num);
                $check_order_together = Model_Api_V2_Together::check_order_together($together_id, $member_id, $together_params);
                if (!$check_order_together['status']) {
                    throw new Exception($check_order_together['msg']);
                }
                $together_info              = $check_order_together['data'];
                $together_price             = $together_info['price'];
                $ticket_price['adultprice'] = $together_price['adult_price'];
            }
        }

        $extend_data = array();
        if (isset($together_info)) {
            $extend_data['together_info'] = $together_info;
        }

        return array($info, $suit_info, $ticket_price, $extend_data);
    }

    /**
     * 初始化订单数据
     * @param $request_param
     * @param $spot
     * @param $suit_info
     * @param $user_info
     * @return array
     */
    public static function make_order_info($request_param, $spot, $suit_info, $user_info)
    {
        $type_id = self::$_typeid;

        $link_info = json_decode($request_param['link_info'], true);

        $order= array(
            'webid' => 0,
            'addtime' => time(),
            'typeid' => $type_id,
            'ordersn' => St_Product::get_ordersn("0{$type_id}"),
            'litpic' => $spot['litpic'],
            'productaid' => $spot['aid'],
            'productname' => $spot['title'],
            'suit_name' => $suit_info['title'],
            'paytype' => $suit_info['paytype'],
            'dingjin' => $suit_info['paytype'] == 2 ? $suit_info['dingjin'] : 0,
            'childprice' => 0,
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'pay_way' => $suit_info['pay_way'],
            'need_confirm' => $suit_info['need_confirm'],
            'status' => $suit_info['need_confirm'] ? 0 : 1,
            'auto_close_time' => $suit_info['auto_close_time'] ? $suit_info['auto_close_time'] + time() : 0,
            'auto_confirm_time' => $suit_info['auto_confirm_time'] ? $suit_info['auto_confirm_time'] + time() : 0,
            'productautoid' => $request_param['product_id'],
            'dingnum' => $request_param['ding_num'],
            'suitid' => $request_param['suit_id'],
            'source' => $request_param['source'],
            'usedate' => $request_param['use_date'],
            'linkman' => $link_info['name'],
            'linktel' => $link_info['phone'],
            'linkemail' => empty($link_info['linkemail']) ? '' : $link_info['linkemail'],
            'remark' => $request_param['remark'],
            'memberid' => $user_info['mid'],
            'jifenbook' => $spot['jifenbook_id'],
            'jifencomment' => ($comment = Model_Jifen::get_used_jifencomment($type_id)) ? $comment['value'] : 0,
            'refund_restriction' => $suit_info['refund_restriction'],
        );

        // 自动关闭订单时间
        $auto_close_time = $suit_info['auto_close_time'] ?: 0;
        if ($auto_close_time) {
            $order['auto_close_time'] = $auto_close_time + time();
        }
        // 待确认时限
        $auto_confirm_time = $suit_info['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
            $order['auto_confirm_time'] = $auto_confirm_time + time();
        }
        //自动退款时限
        $use_date=trim($request_param['use_date']);
        $no_confirm_refund = $suit_info['no_confirm_refund'] ?: 0;
        if ($no_confirm_refund) {
            $order['no_confirm_refund'] = strtotime($use_date . ' +1 day') -  $no_confirm_refund ;
        }
        return  $order;
    }

    /**
     * 获取报价
     * @return array
     */
    public static function get_prices()
    {
        $data = DB::select()
            ->from('spot_pricelist')
            ->where('webid', '=', 0)
            ->order_by('min', 'asc')
            ->execute()
            ->as_array();
        foreach ($data as &$row) {
            if ($row['min'] != '' && $row['max'] != '') {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '-' . Currency_Tool::symbol() . $row['max'];
            } else if ($row['min'] == '') {
                $row['name'] = Currency_Tool::symbol() . $row['max'] . '以下';
            } else if ($row['max'] == '') {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '以上';
            }
        }
        return $data;
    }

    /**
     * 获取全部景点属性
     * @return array
     */
    public static function get_attributes()
    {
        $data = self::get_attribute_by_pid();
        foreach ($data as &$item) {
            $item['child'] = self::get_attribute_by_pid($item['id']);
        }
        return $data;
    }


    /**
     * 通过pid获取下级全部属性
     * @param $pid
     * @return array
     */
    public static function get_attribute_by_pid($pid = 0)
    {
        return DB::select('id', array('attrname', 'name'))
            ->from('spot_attr')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    /**
     * 处理景点预订天数说明
     * @param $info
     * @return void
     */
    public static function calc_days(&$info)
    {
        $time = time();
        foreach ($info['suit_list'] as &$item) {
            if ($item['day_before'] == 0) {
                // 小时分钟均为00时，表示可以在23：59：59秒前预订
                if ($item['hour_before'] == 0 && $item['minute_before'] == 0) {
                    $item['hour_before']   = 23;
                    $item['minute_before'] = 59;
                }
                $item['book_tips'] = $time < strtotime(date('Y-m-d') . " {$item['hour_before']}:" . ($item['minute_before'] ? $item['minute_before'] : '00')) ? '可订今日票' : '可订明日票';
            } elseif ($item['day_before'] == 1) {

                if ($time < strtotime(date('Y-m-d') . " {$item['hour_before']}:" . ($item['minute_before'] ? $item['minute_before'] : '00')) || !$item['hour_before']) {
                    $item['book_tips'] = '可订明日票';
                } else {
                    $item['book_tips'] = '可订后日票';
                }
            } elseif ($item['day_before'] > 1) {
                if ($time < strtotime(date('Y-m-d') . " {$item['hour_before']}:" . ($item['minute_before'] ? $item['minute_before'] : '00')) || !$item['hour_before']) {
                    $item['book_tips'] = sprintf('可订%s票', date('m月d日', strtotime("+{$item['day_before']} days")));
                } else {
                    $item['day_before']++;
                    $item['book_tips'] = sprintf('可订%s票', date('m月d日', strtotime("+{$item['day_before']} days")));
                }

            } else {
                $item['book_tips'] = '';
            }
        }
    }

    /**
     * 获取门票类型数据
     * @param $ticket_type_id
     * @return mixed|null
     */
    public static function get_ticket_type($ticket_type_id)
    {
        return DB::select()
            ->from('spot_ticket_type')
            ->where('id', '=', $ticket_type_id)
            ->execute()
            ->current();
    }

    /**
     * 获取页面预订详情
     * @param $suit_id
     * @return string[]
     * @throws Exception
     */
    public static function book_suit_info($suit_id)
    {
        $ticket_info = Model_Spot_Ticket::get_on_sale_ticket(array('ticket_id' => $suit_id));
        if (!$ticket_info) {
            throw new Exception('套餐不存在或已下架');
        }

        $spot = DB::select()
            ->from('spot')
            ->where('id', '=', $ticket_info['spotid'])
            ->execute()
            ->current();
        if (!$spot) {
            throw new Exception('景点不存在');
        }

        if($spot['is_open_multiple_ticket'] == 1) {
            if($spot['multiple_rule_ticket_id'] && $spot['multiple_rule_ticket_id'] != $suit_id) {
                $multiple_ticket_info = DB::select()
                    ->from('spot_ticket')
                    ->where('id','=', $spot['multiple_rule_ticket_id'])
                    ->execute()
                    ->current();
                $ticket_info = $multiple_ticket_info ?: $ticket_info;
            }
        }

        $data = array(
            'id' => $ticket_info['id'],
            'title' => $ticket_info['title'],
            'spotid' => $ticket_info['spotid'],
            'paytype' => $ticket_info['paytype'],
            'refund_restriction' => $ticket_info['refund_restriction'],
            'need_confirm' => $ticket_info['need_confirm'],
            'effective_days' => $ticket_info['effective_days'],
            'fill_tourer_type' => $ticket_info['fill_tourer_type'],
            'pay_way' => $ticket_info['pay_way'],
            'get_ticket_way' => $ticket_info['get_ticket_way'],
            'supplierlist' =>  $ticket_info['supplierlist'] ?: 0,
            'is_open_multiple_ticket' => $spot['is_open_multiple_ticket'],
            'multiple_rule_ticket_id' => $spot['multiple_rule_ticket_id'],
            'at_least' => $ticket_info['at_least'],
            'fill_link_man' => !empty($ticket_info['fill_link_man']) ? explode(',', $ticket_info['fill_link_man']) : array()
        );

        // 多套餐预订处理
        if ($spot['is_open_multiple_ticket'] == 1) {
            // 没有供应商
            $data['supplierlist'] = 0;

            // 不支持订金支付
            if ($data['paytype'] == 2) {
                $data['paytype'] = 1;
            }
        }

        // 支付方式
        $data['paytype_name'] = Model_Member_Order::get_paytype_name($data['paytype']);

        // 描述
        $data['description']             = Model_Api_V2_Xcx::filter_content($ticket_info['description']);

        // 退款规则
        $refund_class                    = Service_Refund_Rule_Factory::get_instance(Model_Spot::$typeid);
        $data['refund_rule']             = $refund_class->get_format_refund_rule($suit_id);
        $data['refund_restriction_name'] = $refund_class->get_refund_restriction_name($ticket_info['refund_restriction']);
        $data['people_rule']             = Model_Spot_Ticket_People_Rule::get_ticket_people_rule($suit_id);

        // 提前天数
        $in_advance_book_type = Model_Spot_Ticket::IN_ADVANCE_BOOK_BEFORE;
        if (in_array($ticket_info['in_advance_book_type'], $in_advance_book_type)) {
            $data['day_before'] = $ticket_info['day_before'];
        }

        //供应商信息
        $supplier_id       = $data['supplierlist'];
        $data['suppliers'] = [];
        if ($supplier_id) {
            if (Model_Supplier::display_is_open()) {
                $supplier = DB::select('id', 'litpic', 'suppliername')
                    ->from('supplier')
                    ->where('id', '=', $supplier_id)
                    ->execute()
                    ->current();
                $data['suppliers'] = $supplier;
            }
        }

        // 报价
        $price_arr         = Model_Spot::get_minprice($ticket_info['spotid'], $ticket_info['id']);
        $data['ourprice']  = $price_arr['price'];//最低价
        $data['sellprice'] = $price_arr['sellprice'];//原价

        // 门票类型
        $type                     = Model_Api_V2_Spot::get_ticket_type($ticket_info['tickettypeid']);
        $data['ticket_type_name'] = !empty($type) ? $type['kindname'] : '';

        // 预订提示
        $data['book_tips'] = Model_Spot_Suit::calc_days($ticket_info);

        // 景点名称
        $data['spot_name'] = $spot['title'];

        // 订金
        $data['dingjin'] = $ticket_info['dingjin'] ? Currency_Tool::price($ticket_info['dingjin']) : 0;

        ksort($data);

        return $data;
    }

    /**
     * 添加订单规格信息
     * @param $sku_id
     * @param $order_id
     * @param $product_id
     * @param $suit_id
     * @return void
     * @throws Kohana_Exception
     */
    public static function add_order_sku($sku_id, $order_id, $product_id, $suit_id)
    {
        $sku = MOdel_Spot_Ticket_Sku::get_sku_info($sku_id);
        if ($sku) {
            $data = array(
                'order_id' => $order_id,
                'product_id' => $product_id,
                'suit_id' => $suit_id,
                'sku_id' => $sku_id,
                'sku_info' => json_encode($sku),
                'addtime' => time()
            );
            DB::insert('member_order_sku', array_keys($data))
                ->values(array_values($data))
                ->execute();
        }
    }
}